package mornd.test4;

import org.springframework.core.GenericTypeResolver;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.Arrays;

/**
 * @author: mornd
 * @dateTime: 2023/5/8 - 0:11
 * 获取父类泛型的两种方式
 */
public class Demo {
    public static void main(String[] args) {
        /*
            方式一：jdk获取
         */
        //Class<? super UserDao> superclass = UserDao.class.getSuperclass(); // 获取父类，不带泛型信息
        //System.out.println(superclass);// class mornd.test4.Demo$BaseDao
        Type genericSuperclass = UserDao.class.getGenericSuperclass(); // 获取带有泛型信息的父类
        //System.out.println(genericSuperclass); // mornd.test4.Demo.mornd.test4.Demo$BaseDao<mornd.test4.Demo$User>

        if(genericSuperclass instanceof ParameterizedType) {
            ParameterizedType type = (ParameterizedType) genericSuperclass;
            Type[] actualTypeArguments = type.getActualTypeArguments();
            System.out.println(Arrays.toString(actualTypeArguments));
        } else {
            System.out.println("没有泛型信息");
        }

        System.out.println("--------------");

        /*
            方式二：spring 获取
         */
        Class<?>[] classes =
                GenericTypeResolver.resolveTypeArguments(UserDao.class, BaseDao.class);
        System.out.println(Arrays.toString(classes));

    }

    static class BaseDao<T> {
        T getOne() {return null;};
    }

    static class UserDao extends BaseDao<User> {
        @Override
        User getOne() {
            return super.getOne();
        }
    }

    static class RoleDao extends BaseDao {
        @Override
        Object getOne() {
            return super.getOne();
        }
    }

    static class User {}
}
